<script setup lang="ts">
import { PropType, reactive, watch } from "vue";
import { DEFAULT_FIELD_NAMES } from "./define";
import type { FieldNamesProp } from "./define";
import WebxMenuSub from "./sub.vue";

defineOptions({ name: "WebxMenu" });
const emits = defineEmits(["click:menu", "update:selectedKeys", "update:openKeys"]);
const props = defineProps({
  // 字段名映射关系
  fieldNames: {
    type: Object as PropType<FieldNamesProp>,
    default: () => DEFAULT_FIELD_NAMES
  },
  // 菜单数组
  menuData: { type: Array as PropType<any[]>, default: () => [] },
  // 当前选中的菜单keys
  selectedKeys: { type: Array as PropType<string[]>, default: () => [] },
  // 当前展开的菜单keys
  openKeys: { type: Array as PropType<string[]>, default: () => [] },
  // 菜单是否折叠
  collapsed: { type: Boolean, default: false },
  // 菜单点击执行回调
  clickMenuFn: { type: Function as PropType<(...args: any[]) => void>, default: () => null }
});
// 菜单栏数据
const aMenuData = reactive({
  selectedKeys: [] as string[],
  openKeys: [] as string[]
});

watch(
  () => props.selectedKeys,
  newKeys => {
    aMenuData.selectedKeys = newKeys;
  }
);
watch(
  () => props.openKeys,
  newKeys => {
    aMenuData.openKeys = newKeys;
  }
);
watch(
  () => aMenuData.selectedKeys,
  newKeys => {
    emits("update:selectedKeys", newKeys);
  }
);
watch(
  () => aMenuData.openKeys,
  newKeys => {
    emits("update:openKeys", newKeys);
  }
);
</script>

<template>
  <AMenu
    :selectedKeys="aMenuData.selectedKeys"
    mode="inline"
    :openKeys="aMenuData.openKeys"
    :inlineIndent="12"
    style="border: none"
  >
    <template v-for="menu in menuData">
      <template v-if="!menu[fieldNames.children] || menu[fieldNames.children].length === 0">
        <AMenuItem :key="menu[fieldNames.key]" @click="clickMenuFn(menu)">
          <div class="flex items-center gap-2">
            <WebxIcon :name="menu[fieldNames.icon]" />
            <span v-if="!collapsed">{{ menu[fieldNames.name] }}</span>
          </div>
        </AMenuItem>
      </template>
      <template v-else>
        <WebxMenuSub
          :key="menu[fieldNames.key]"
          :menuInfo="menu"
          :fieldNames="fieldNames"
          :collapsed="collapsed"
          :clickMenuFn="clickMenuFn"
        />
      </template>
    </template>
  </AMenu>
</template>

<style lang="less" scoped></style>
